<?php

namespace app\admin\controller;

use app\admin\model\Course;
use app\admin\model\CourseTag;
use app\admin\model\Tag;
use app\admin\model\Coursecate;
use app\admin\model\Chapter;
use think\Controller;
use think\Request;

class Courses extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->assign([
            'taglists' => Coursecate::with('tags')->select(),
            'course_manage' => 'am-in',
            '_course' => 'am-active'
        ]);

    }

    /**
     * 显示资源列
     */
    public function index()
    {
        //
        $courses = Course::with('photo')->with('tags')->withCount('chapters')->paginate(10);
//        return $courses->count();
//        return json($courses);
        return view('index', compact('courses'));

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
//        return json(Coursecate::with('tags')->select());

        return view('create');
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $course = Course::create($request->param());
        $course->tags()->saveAll($request->param()['tag_id']);
        return redirect('index');
    }

    /**
     * 显示编辑资源表单页.
     */
    public function edit($id)
    {
        //
        $course = Course::with('photo')->with('tags')->find($id);
//        return json($course);
        //这里取当前课程下对应的tag值有两种方法。一种是用到中间模型，比较麻烦，一下是最直接的办法。
//        $tag_id = CourseTag::where('course_id', $id)->column('tag_id');
        $tag_id = $course->tags->column('id');
        return view('edit', compact('course', 'tag_id'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
//        return json($request->param());
        $course = Course::find($id);
        $course->tags()->sync($request->param()['tag_id']);
        $course->update($request->param());
        return redirect('index');
    }

    /**
     * 删除指定资源
     *
     */
    public function delete($id)
    {
        //
        Course::with('photo')->with('tags')->destroy($id);
        return redirect('index');
    }
}
